package ru.batrdmi.svnplugin.gui;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

public class ScrollOverlayFactory {
    public static JComponent addOverlay(final JScrollPane scrollPane, final JComponent overlay,
                                        final boolean scrollHorizontally, final boolean scrollVertically) {
        JLayeredPane panel = new JLayeredPane();
        panel.setLayout(new OverlayLayout(panel));
        final JViewport viewport = scrollPane.getViewport();
        final JComponent c = new JComponent() {
            @Override
            public void paintComponent(Graphics g) {
                Point p = viewport.getViewPosition();
                Rectangle r = viewport.getBounds();
                Graphics gc = g.create(r.x, r.y, r.width, r.height);
                try {
                    gc.translate(scrollHorizontally ? -p.x : 0, scrollVertically ? -p.y : 0);
                    overlay.paint(gc);
                } finally {
                    gc.dispose();
                }
            }
        };
        panel.add(c, JLayeredPane.PALETTE_LAYER);
        panel.add(scrollPane, JLayeredPane.DEFAULT_LAYER);
        viewport.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                Rectangle r = viewport.getBounds();
                overlay.setBounds(r);
                c.repaint();
            }
        });
        return panel;    }
}
